<div id="html-template" class="hide">
    <li class="commodity-comment">
        <div class="comment-avatar-block"><img class="avatar" src="" alt="用户头像" style="max-width:100%; max-height:100%"/></div>
        <div class="comment-main-block">
            <div class="username">#username#</div>
            <div class="time">#time#</div>
            <div><span class="private"></span><span class="father-comment-username"></span><span class="comment-content">#content#</span></div>
            <a href="javascript:" class="leave-comment-reply-btn">回复</a>
        </div>
        <form class="leave-commodity-comment" method="post" style="display: none">
            <div class="form-content" style="overflow: hidden">
                <input type="hidden" name="commodity_id">
                <input type="hidden" name="father_id">

                <div class="input-group">
                    <label class="input-group-addon sr-only">回复</label>
                    <textarea name="content" class="form-control reply-textarea" placeholder="请输入回复内容" required="required"></textarea>
                </div>
                <div class="pull-right">
                    <input type="checkbox" name="private" style="vertical-align:-2px"/>
                    <span class="secret-txt">密谈</span>
                    <input type="submit" class="btn btn-primary" value="发表"/>
                </div>
            </div>
        </form>
        <ul class="sub-comment-block"></ul>
    </li>
    <div class="load-more-comment-block">加载更多……</div>
</div>

<?php /** @var User $CurrentUser */ ?>
<input type="hidden" value="<?php echo ($CurrentUser->getPower() < 1) ? '0' : '1'; ?>" id="ifpower"/>
<?php if (isset($CommodityArray) && sizeof($CommodityArray) > 0) : ?>
    <?php foreach ($CommodityArray as $index => $thisCommodity): ?>
        <?php /** @var Commodity $thisCommodity */ ?>
        <?php if (!$thisCommodity) continue; ?>
        <?php /** @var User $thatUser */ ?>
        <?php if (!$thatUser = $thisCommodity->getUser()) continue; ?>
        <?php if ($thisCommodity->getStock() <= 0) continue; ?>
        <div id="commodity-<?php echo $thisCommodity->getId() ?>" class="commodity" data-commodity-id="<?php echo $thisCommodity->getId() ?>">
            <a class="user-info" href="<?php echo base_url('home/userCenter/commodity/' . $thatUser->getId()) ?>">
                <img class="user-avatar-small" src="<?php echo $thatUser->getDisplayAvatarUrl() ?>" alt="头像"/>
                <span class="username"><?php echo $thatUser->getDisplayName(); ?></span>
            </a>

            <div class="commodity-image-block">
                <a  href="<?php echo base_url('home/details/' . $thisCommodity->getId()) ?>"><img src="<?php echo $thisCommodity->getDisplayImageUrl(); ?>" alt="商品预览图"/></a>
            </div>
            <div class="commodity-content-block">
                <h3 class="commodity-name">
                    <a class="text-primary" title="<?php echo $thisCommodity->getTitle(); ?>" href="<?php echo base_url('home/details/' . $thisCommodity->getId()) ?>"><?php echo $thisCommodity->getTitle(); ?></a>
                </h3>

                <div class="commodity-intro"><?php echo $thisCommodity->getIntro(); ?></div>
                <div class="commodity-param">
                    <div class="state"><?php echo $thisCommodity->getDisplayReleaseType(); ?></div>
                    <div class="price"><span class="RMB"><?php echo $thisCommodity->getDisplayPrice(); ?></span></div>
                    <div class="num"><?php echo $thisCommodity->getDisplayStock(); ?></div>
                    <?php if (isset($CurrentUser) && $CurrentUser->getId() > 0): ?>
                        <?php switch ($thisCommodity->getContactType()) :
                            case _ContactType_LongPhone:
                            case _ContactType_ShortPhone:
                                ?>
                                <div class="contact_phone"><?php echo $thisCommodity->getDisplayContactInfo(); ?></div>
                                <?php
                                break;
                            case _ContactType_Qq:
                                ?>
                                <a class="contact_qq" target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=<?php echo $thisCommodity->getDisplayContactInfo(); ?>&site=qq&menu=yes"><?php echo $thisCommodity->getDisplayContactInfo(); ?></a>
                                <?php
                                break;
                            case _ContactType_None:
                            default :
                                ?>
                                    <div class="contact_no"><?php echo $thisCommodity->getDisplayContactInfo(); ?></div>
                                <?php
                        endswitch;
                        ?>
                    <?php else: ?>
                        <div class="contact_phone"><a class="signIn" href="javascript:" style="text-decoration:underline; line-height:22px;">登录后查看</a></div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="meta">
                <div class="pull-left">
                    <span class="time"><span class="glyphicon glyphicon-time"></span>&nbsp;<span class="timeago" title="<?php echo $thisCommodity->getReleaseTime(); ?>"><?php echo $thisCommodity->getReleaseTime(); ?></span></span>
                    <span class="form-here"><?php
                        if ($currentSchool['schoolid'] == 0) {
                            //注意:可能会有性能问题--kwan
                            $_commodity_school_unicode = $thisCommodity->getSchoolunicode();
                            $_commodity_school = School_Model::getSchoolByUnicode($_commodity_school_unicode);
                            if ($_commodity_school) {
                                echo '来自' . $_commodity_school->getName();
                            }
                        }
                        ?>
                    </span>
                </div>
                <div class="pull-right" style="position:relative;">
                    <div class="share-box">
                        <div class="share-to">
                            <a href="<?php echo base_url('api/share?type=weibo&commodity_id=' . $thisCommodity->getId()) ?>"><img src="<?php echo base_url('public/images/icon/details/weibo.png') ?>" title="分享到微博"/></a>
                        </div>
                        <a href="javascript:" class="share-a"><span class="glyphicon glyphicon-share"></span>分享</a><span class="top_line">|</span>
                    </div>
                    <?php if (isset($CurrentUser) && $CurrentUser->getId() > 0 && $thisCommodity->isCommodityPlusOneExistWithUserId($CurrentUser->getId())): ?>
                        <a href="javascript:" class="commodity-toggle-plus-one" data-commodity-id="<?php echo $thisCommodity->getId() ?>"><span class="glyphicon glyphicon-thumbs-up"></span>已赞(<?php echo $thisCommodity->getPlusOneCount() ?>)</a>
                        <span class="top_line">|</span>
                    <?php else : ?>
                        <a href="javascript:" class="commodity-toggle-plus-one" data-commodity-id="<?php echo $thisCommodity->getId() ?>"><span class="glyphicon glyphicon-thumbs-up"></span>赞(<?php echo $thisCommodity->getPlusOneCount() ?>)</a>
                        <span class="top_line">|</span>
                    <?php endif; ?>
                    <?php if (isset($CurrentUser) && $CurrentUser->getId() > 0 && $thisCommodity->isCommodityFavoriteExistWithUserId($CurrentUser->getId())): ?>
                        <a href="javascript:" class="commodity-toggle-favorite" data-commodity-id="<?php echo $thisCommodity->getId() ?>"><span class="glyphicon glyphicon-heart"></span>已收藏</a><span class="top_line">|</span>
                    <?php else : ?>
                        <a href="javascript:" class="commodity-toggle-favorite" data-commodity-id="<?php echo $thisCommodity->getId() ?>"><span class="glyphicon glyphicon-heart"></span>收藏</a><span class="top_line">|</span>
                    <?php endif; ?>
                    <a href="javascript:" class="show-comment" data-commodity-id="<?php echo $thisCommodity->getId() ?>"><span class="glyphicon glyphicon-comment"></span>留言(<span class="comment-count"><?php echo $thisCommodity->getCommodityCommentCount() ?></span>)</a>
                </div>
            </div>

            <div class="clearfix"></div>

            <div class="comment">
                <div class="leave-comment">
                    <?php if (isset($CurrentUser) && $CurrentUser->getId() !== 0): ?>
                        <form class="leave-commodity-comment" method="post" data-master-comment-id="0">
                            <div class="form-content" style="overflow: hidden">
                                <input type="hidden" name="commodity_id" value="<?php echo $thisCommodity->getId() ?>">
                                <input type="hidden" name="father_id" value="0">

                                <div class="input-group">
                                    <label class="input-group-addon sr-only">回复</label>
                                    <textarea name="content" class="form-control reply-textarea" placeholder="请输入回复内容" required="required"></textarea>
                                </div>
                                <div class="pull-right">
                                    <input type="checkbox" name="private" style="vertical-align:-2px"/>
                                    <span class="secret-txt">密谈</span>
                                    <input type="submit" class="btn btn-primary" value="发表"/>
                                </div>
                            </div>
                        </form>
                    <?php else: ?>
                        <div class="comment-user-nologin">
                            要留言？请先&nbsp;&nbsp;<a class="signIn" href="javascript:">登录</a>&nbsp;&nbsp;或&nbsp;&nbsp;<a class="signUp" href="javascript:">注册</a>
                        </div>
                    <?php endif; ?>
                </div>
                <ul class="list-comment list-unstyled"></ul>
            </div>
        </div>
        <div class="clearfix"></div>
    <?php endforeach; ?>
<?php else: ?>
    <div>
        <h1 class="alert alert-success text-center">Sorry，暂时没有您要的信息！<a class="changeschool" href="###">去其他学校看看</a></h1>
    </div>
<?php endif; ?>

<script>
function appendCommodityComment($block, comment, fatherUsername, masterCommentId) {
    var $comment = $('#html-template').find('.commodity-comment').clone().addClass('hide').appendTo($block);
    $comment.attr('id', 'commodity-comment-' + comment.id);
    $comment.attr('data-comment-id', comment.id);
    $comment.find('.avatar').attr('src', comment.userAvatarUrl);
    $comment.find('.username').html(comment.userDisplayName);
    $comment.find('.time').html(comment.releaseTime);
    $comment.find('.comment-content').html(comment.content);
    $comment.find('form.leave-commodity-comment-reply').attr('data-ajax-append-id', masterCommentId);
    var $leaveCommentForm = $comment.find('.leave-commodity-comment');
    $leaveCommentForm.attr('data-father-name', comment.userDisplayName);
    $leaveCommentForm.attr('data-master-comment-id', masterCommentId);
    $leaveCommentForm.find('input[name=commodity_id]').val(comment.commodityId);
    $leaveCommentForm.find('input[name=father_id]').val(comment.id);
    if (comment.private == true)
        $comment.find('.private').html('[密谈]');
    if (fatherUsername)
        $comment.find('.father-comment-username').html('@' + fatherUsername);
    return $comment;
}

function appendCommodityCommentByCommentSet(commentSet) {
    var perPage = 4;
    var commodityId = commentSet.commodityId;
    var $commentList = $('#commodity-' + commodityId).find('.list-comment');
    var i = 0;
    commentSet.masterCommentIdArraySortByReleaseTime.forEach(function (commentId) {
        var comment = commentSet.comments[commentId];
        if (comment) {
            var $comment = appendCommodityComment($commentList, comment, undefined, comment.id);
            var $subCommentBlock = $comment.find('.sub-comment-block');
            var j = 0;
            comment.descendantCommentIdArraySortByReleaseTime.forEach(function (subCommentId) {
                var subComment = commentSet.comments[subCommentId];
                $sub = appendCommodityComment($subCommentBlock, subComment, commentSet.comments[subComment.fatherId] ? commentSet.comments[subComment.fatherId].userDisplayName : undefined, comment.id);
                if (j < perPage) {
                    $sub.removeClass('hide');
                }
                if (j == perPage) {
                    $sub.removeClass('hide');
                    appendLoadMoreCommodityCommentBlock($sub);
                }
                j++;
            });
            if (i < perPage) {
                $comment.removeClass('hide');
            }
            if (i == perPage) {
                $comment.removeClass('hide');
                appendLoadMoreCommodityCommentBlock($comment);
            }
            i++;
        }
    });
}

function appendCommodityCommentByCommodityId(commodity_id) {
    CommodityCommentSet.InitByCommodityId(commodity_id, appendCommodityCommentByCommentSet);
}

function appendLoadMoreCommodityCommentBlock($block) {
    var $loadMoreBtn = $('#html-template').find('.load-more-comment-block').clone();
    $loadMoreBtn = $($block).after($loadMoreBtn);
    $loadMoreBtn.removeClass('hide');
    return $loadMoreBtn;
}

function hideAllLeaveCommentForm() {
    $('form.leave-commodity-comment[data-master-comment-id!=0]').slideUp();
}

$(document).on('submit', 'form.leave-commodity-comment', function (event) {
    event.preventDefault();
    var ifpower = $("#ifpower").val();
    if (ifpower == 0) {
        noty({
            type: 'warning',
            text: '请先激活邮箱帐号，并进行实名认证，Lets Go？',
            buttons: [
                {
                    addClass: 'btn btn-sm btn-danger', text: '确定',
                    onClick: function ($noty) {
                        $noty.close();
                        window.location.href = base_url('home/userCenter#resendemail');
                    }
                },
                {
                    addClass: 'btn btn-sm btn-default', text: '取消',
                    onClick: function ($noty) {
                        $noty.close();
                    }
                }
            ]
        });
    }
    else {
        var form = this;
        var fatherName = $(form).data('father-name');
        var masterCommentId = $(form).data('master-comment-id');
        $.ajax({
            url: base_url('api/leaveCommodityComment'),
            type: 'post',
            data: $(form).serialize(),
            success: function (jsonrsp) {
                try {
                    var rsp = $.parseJSON(jsonrsp);
                    switch (rsp.type) {
                        case 'success':
                            noty({type: rsp.type, text: rsp.message});
                            var $commentCount = $(form).closest('.commodity').find('.comment-count');
                            var commentCount = $commentCount.text();
                            $commentCount.text(+commentCount + +1);
                            $(form).find('[name=content]').val('');
                            var comment = CommodityComment.InitByJsonData(rsp.data);
                            hideAllLeaveCommentForm();
                            var $comment = undefined;
                            if (masterCommentId != 0)
                                $comment = appendCommodityComment($('#commodity-comment-' + masterCommentId).children('.sub-comment-block'), comment, fatherName, masterCommentId);
                            else
                                $comment = appendCommodityComment($('#commodity-' + comment.commodityId).find('.list-comment'), comment, fatherName, comment.id);
                            $comment.removeClass('hide');
                            break;
                        default:
                            noty({type: rsp.type, text: rsp.message});
                            break;
                    }
                } catch (ex) {
                    noty({type: 'error', text: '发生内部错误，请联系管理员'});
                    throw ex;
                }
            }
        });
    }
});

$(document).on('click', '.show-comment', function () {
    var commodityId = $(this).data('commodity-id');
    var $thisCommodity = $('#commodity-' + commodityId);
    var $comment = $thisCommodity.find('.comment');
    var $commentList = $comment.find('.list-comment');
    if ($comment.css('display') == 'none') {
        $commentList.empty();
        $comment.slideDown('fast');
        $(this).css('color', 'rgb(255, 250, 148)');
        appendCommodityCommentByCommodityId(commodityId);
    } else {
        $comment.slideUp('fast');
        $(this).removeAttr('style');
    }
});

$(document).on('click', '.load-more-comment-block', function () {
    var perClickLoadNum = 5;
    $(this).nextAll('.commodity-comment.hide').each(function (k, v) {
        if (k < perClickLoadNum) {
            $(v).removeClass('hide');
        }
        if (k == perClickLoadNum) {
            appendLoadMoreCommodityCommentBlock($(v));
        }
    });
    $(this).remove();
});

$(document).on('click', '.commodity-toggle-plus-one', function () {
    var _this = this;
    var commodityId = $(this).data('commodity-id');
    $.ajax({
        url: '<?php echo base_url('api/commodityTogglePlusOne');?>',
        type: 'get',
        data: {commodity_id: commodityId},
        beforeSend: function () {
        },
        complete: function () {
        },
        success: function (jsonrsp) {
            try {
                var rsp = $.parseJSON(jsonrsp);
                switch (rsp.type) {
                    case 'success':
                        if (rsp.data.isCommodityPlusOneNow) {
                            $(_this).html('<span class="glyphicon glyphicon-thumbs-up"></span>已赞(' + rsp.data.countCommodityPlusOneNow + ')');
                        } else {
                            $(_this).html('<span class="glyphicon glyphicon-thumbs-up"></span>赞(' + rsp.data.countCommodityPlusOneNow + ')');
                        }
                        break;
                    case 'error':
                        if (rsp.message == 'NOTLOGIN') {
                            showDialog('login');
                        }
                        break;
                    default:
                        break;
                }
            } catch (ex) {
                noty({type: 'error', text: '发生内部错误，请联系管理员'});
                throw ex;
            }
        }
    });
});

$(document).on('click', '.commodity-toggle-favorite', function () {
    var _this = this;
    var commodityId = $(this).data('commodity-id');
    $.ajax({
        url: '<?php echo base_url('api/commodityToggleFavorite');?>',
        type: 'get',
        data: {commodity_id: commodityId},
        beforeSend: function () {
        },
        complete: function () {
        },
        success: function (jsonrsp) {
            try {
                var rsp = $.parseJSON(jsonrsp);
                switch (rsp.type) {
                    case 'success':
                        if (rsp.data.isCommodityInFavoriteNow) {
                            $(_this).html('<span class="glyphicon glyphicon-heart"></span>已收藏');
                        } else {
                            $(_this).html('<span class="glyphicon glyphicon-heart"></span>收藏');
                        }
                        break;
                    case 'error':
                        if (rsp.message == 'NOTLOGIN') {
                            showDialog('login');
                        }
                        break;
                    default:
                        break;
                }
            } catch (ex) {
                noty({type: 'error', text: '发生内部错误，请联系管理员'});
                throw ex;
            }
        }
    });
});

$(document).on('click', '.leave-comment-reply-btn', function () {
    var commodityId = $(this).closest('.commodity').data('commodity-id');
    var commentId = $(this).closest('.commodity-comment').data('comment-id');
    var $comment = $(this).closest('li#commodity-comment-' + commentId);
    var $leaveComment = $comment.children('.leave-commodity-comment');
    if ($leaveComment.css('display') == 'none') {
        hideAllLeaveCommentForm();
        $leaveComment.slideDown();
    } else {
        $leaveComment.slideUp();
    }
});

$(document).on('mouseenter', '.share-box', function () {
    $(this).children(".share-to").css("display", "block");
    $(".share-to").not(this).children(".share-to").css("display", "none");
});
$(document).on('mouseleave', '.share-box', function () {
    $(this).children(".share-to").css("display", "none");
})
</script>